import {
  AppstoreOutlined,
  ControlOutlined,
  HomeOutlined,
  PhoneOutlined,
  UnorderedListOutlined
} from '@ant-design/icons-vue'
import { getMenuList } from '@/apis/system/base'
import { getLocalMenus, setLocalMenus } from '@/utils/local'
import { h } from 'vue'

type menuType = {
  key: string
  icon?: () => any
  label: string
  path?: string
  children?: menuType[]
}
/*
  menuId
  menuType = 'M' / 'C' 是菜单, 'F'是功能权限
  name
  parentId
  path
  icon
*/
type IconName = keyof typeof iconMap
const iconMap = {
  HomeOutlined,
  AppstoreOutlined,
  ControlOutlined,
  PhoneOutlined,
  UnorderedListOutlined
}
const transformTree = (tree: any) => {
  return tree.map((node: any) => {
    const isPermission = node.children && node.children.find((item: any) => item.menuType === 'F')
    const iconName: IconName = (node.iconName || 'HomeOutlined') as IconName
    return {
      label: node.name,
      key: node.menuId,
      path: node.path,
      icon: node.menuType === 'M' ? () => h(iconMap[iconName]) : undefined,
      iconName: node.iconName,
      menuType: node.menuType,
      parentId: node.parentId,
      children: node.children && !isPermission ? transformTree(node.children) : undefined // 递归处理子节点
    }
  })
}
export const getMenus = () => {
  const menuArr = getLocalMenus()
  if (menuArr) {
    const arr = JSON.parse(menuArr)
    arr.forEach((item: any) => {
      const iconName: IconName = (item.iconName || 'HomeOutlined') as IconName
      item.icon = () => h(iconMap[iconName])
    })
    return arr
  }
  return new Promise(async (resolve) => {
    const res = await getMenuList({})
    const menuArr = [
      {
        key: 0,
        icon: () => h(HomeOutlined),
        label: '首页',
        path: '/',
        iconName: 'HomeOutlined'
      },
      ...transformTree(res.data)
    ]
    setLocalMenus(JSON.stringify(menuArr))
    return resolve(menuArr)
  })
}
